import { Injectable } from "@nestjs/common"
import { JwtService } from '@nestjs/jwt';
import * as svgCaptcha from 'svg-captcha';
import { UsersService } from "../users/user.service";
import * as bcrypt from 'bcrypt';


@Injectable()
export class LoginService {
    private captchaOptions = {
        size: 3, // 验证码长度
        noise: 1, // 干扰线条的数量
        color: true, // 验证码的字符是否有颜色，默认为true
        background: '#fff', // 背景色，默认随机
        width: 100, // 验证码图片的宽度
        height: 35, // 验证码图片的高度
      }
    constructor(
        private jwtService: JwtService,
        private usersService: UsersService,
    ){}

    generateCaptcha() {
        return svgCaptcha.create(this.captchaOptions);
    }
    verifyCaptcha(inputCaptcha: string, sessionCaptcha: string): boolean {
        // 验证用户输入的验证码是否正确
        return inputCaptcha.toLowerCase() === sessionCaptcha.toLowerCase();
      }

    getLogin() {
        return "login"
    }

    async createUser(username, pass) {
        const user = await this.usersService.create(username, pass);
        return user;
    }
    async signIn(username, pass) {
        const user = await this.usersService.findOneByName(username);
        console.log("查询出来的用户----->", user)
        if (!user) {
            return {
                code: 1000,
                data: {},
                message: '用户不存在'
            };
        }
    const checkpass = await bcrypt.compare(pass, user?.password); // true ： 密码一致可以登录， false： 用户传入的密码和数据库的密码不一致，不能登录
        console.log('checkpass--->', checkpass)
        if(!checkpass){
          return {
            code: 1000,
            data: {},
            message: '密码错误'
          }
        }
          console.log('user--->', user)
          const userId = user?._id ? user._id.toString() : '';
          const payload = { username: user.username, sub:  userId};
          return {
            code: 200,
            data:{
              access_token: await this.jwtService.signAsync(payload),
              userId
            },
            message:'登录成功'
          };
      }

      async signup(username, pass) {
        const user = await this.usersService.findOneByName(username);
        console.log("查询出来的用户----->", user)
        if (user) {
            return {
                code: 1000,
                data: {},
                message: '该用户已注册'
            };
        }
        const newUser = await this.usersService.newSignUp(username, pass);
        console.log('newUser--->', newUser)

        const userId = newUser?._id ? newUser._id.toString() : '';
        const payload = { username: newUser?.username, sub:  userId};
        return {
          code: 200,
          data:{
            access_token: await this.jwtService.signAsync(payload),
            userId
          },
          message:'注册且登录成功'
        };
      }
      

}